package com.seven.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seven.mapper.UserMapper;
import com.seven.model.User;
import com.seven.service.UserService;
import com.seven.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean registryUser(User dto) {
        String password = dto.getPassword();
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        dto.setSalt(salt);
        dto.setPassword(md5Password);
        dto.setCreateTime(new Date());
        int i = userMapper.insert(dto);
        return i > 0?true:false;
    }

    @Override
    public String login(User dto) {
        String token = "";
        String username = dto.getUsername();
        String password = dto.getPassword();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        String md5Password = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes());
        if (md5Password.equals(user.getPassword())) {
            token = JwtUtil.createToken(user.getId());
            redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(user), 1, TimeUnit.DAYS);
        }
        return token;
    }

    @Override
    public User checkToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Map<String, Object> map = JwtUtil.checkToken(token);
        if (map == null) {
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isEmpty(userJson)) {
            return null;
        }
        User user = JSON.parseObject(userJson, User.class);
        return user;
    }

}
